from tools_algorithm import *


class Solution:
    def latestTimeCatchTheBus(
        self, buses: List[int], passengers: List[int], capacity: int
    ) -> int:
        buses.sort()
        passengers.sort()
        p, t, c = 0, 0, 1
        for b in buses:
            t = capacity
            for _ in range(capacity):
                if p == len(passengers) or passengers[p] > b:
                    break
                if p > 0 and passengers[p] == passengers[p - 1] + 1:
                    c += 1
                else:
                    c = 1
                p += 1
                t -= 1
        if (p == 0 or passengers[p - 1] < buses[-1]) and t > 0:
            return buses[-1]
        return passengers[p - c] - 1


s = Solution()
print(s.latestTimeCatchTheBus([5], [7, 8], 1))
print(s.latestTimeCatchTheBus([3], [2, 4], 2))
